Cms = {};
/**
 * 获取登录信息
 */
Cms.getLoginUser = function (base, api, toLogin, loginedCallBack) {
  //sessionStorage 中存在token检查token有效期是否到期，在有效期内则显示用户名
  const tokenExpiredTime = sessionStorage.getItem("expiresTime");
  const refreshToken = sessionStorage.getItem("refreshToken");
  if (isExpired(tokenExpiredTime)) {
    if (refreshToken && refreshToken.trim() != "") {
      //不在有效期内则去尝试交互新的token 拿不到新的token则是未登录状态，拿到了则更新token
      axios
        .post(
          api + "/user/refresh-token?refreshToken=" + refreshToken,
          {},
          {
            headers: {
              "Tenant-Id": Cms.getTenantId(),
            },
          }
        )
        .then(function (response) {
          if (response.data.code == 0) {
            sessionStorage.setItem(
              "accessToken",
              response.data.data.accessToken
            );
            sessionStorage.setItem(
              "expiresTime",
              response.data.data.expiresTime
            );
            sessionStorage.setItem(
              "refreshToken",
              response.data.data.refreshToken
            );
            $("#loginAfterDiv").removeClass("d-none");
            $("#loginDiv").addClass("d-none");
          }
        });
    }
    $("#loginAfterDiv").addClass("d-none");
    $("#loginDiv").removeClass("d-none");
    if (toLogin) {
      window.location.href = base + "/login";
    }
  } else {
    validUserInfo(api, loginedCallBack);
  }
};

function validUserInfo(api, loginedCallBack) {
  const token = sessionStorage.getItem("accessToken");
  if (token) {
    axios
      .get(api + "/member/user", {
        headers: {
          "Tenant-Id": Cms.getTenantId(),
          Authorization: "Bearer " + token,
        },
      })
      .then(function (response) {
        if (response.data.code == 0) {
          loginedCallBack(response);
        } else if (response.data.code == 2001500002) {
          //缓存的token过期 用户未登录
          sessionStorage.removeItem("accessToken");
          sessionStorage.removeItem("expiresTime");
          sessionStorage.removeItem("refreshToken");
          sessionStorage.removeItem("userId");
          sessionStorage.removeItem("avatar");
          sessionStorage.removeItem("deptName");
          sessionStorage.removeItem("nickname");
          sessionStorage.removeItem("username");
          $("#loginAfterDiv").removeClass("d-none");
          $("#loginDiv").addClass("d-none");
          window.location.href = "${base}/";
        }
      });
  }
}

Cms.checkChannelPerm = function (base, api, channelId) {
  if (!channelId) {
    return;
  }
  const token = sessionStorage.getItem("accessToken");
  if (token) {
    axios
      .get(api + "/channel/hasChannelPermission?channelId=" + channelId, {
        headers: {
          "Tenant-Id": Cms.getTenantId(),
          Authorization: "Bearer " + token,
        },
      })
      .then(function (response) {
        if (response.data.code == 0 && !response.data.data) {
          window.location.href = base + "/no-auth";
        }
      });
  }
};
Cms.getTenantId = function () {
  return "1";
};
Cms.isValidPhoneNumber = function (phoneNumber) {
  var regex = /^1[3-9]\d{9}$/;
  return regex.test(phoneNumber);
};
Cms.isValidEmail = function (email) {
  var regex =  /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  return regex.test(email);
};

Cms.generateRandomString = function (length) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:\",./<>?';
  let result = '';
  for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      result += characters.charAt(randomIndex);
  }
  return result;
}
Cms.getRandomInt = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
